//
//  UILabel+ZJMasonryKit.m
//  ZJUIKit
//
//  Created by dzj on 2018/1/17.
//  Copyright © 2018年 kapokcloud. All rights reserved.
//

#import "UILabel+ZJMasonryKit.h"
#import <CoreText/CoreText.h>

// 获取屏幕的宽度
#define kScreenWidthLabel ([UIScreen mainScreen].bounds.size.width)
// 不同屏幕尺寸字体适配
#define kScreenWidthRatioLabel  (kScreenWidthLabel / 375.0)
#define AdaptedWidthLabel(x)  ceilf((x) * kScreenWidthRatioLabel)
// 字体适配
#define AdaptedFontSizeLabel(R)     [UIFont systemFontOfSize:AdaptedWidthLabel(R)]

@implementation UILabel (ZJMasonryKit)


+(instancetype)zj_labelWithFontSize:(CGFloat)fontSize{
    return [self zj_labelWithFontSize:fontSize text:nil];
}


+(instancetype)zj_labelWithFontSize:(CGFloat)fontSize text:(NSString *)text{
    return [self zj_labelWithFontSize:fontSize text:text superView:nil constraints:nil];
}


+(instancetype)zj_labelWithFontSize:(CGFloat)fontSize
                      textColor:(UIColor *)textColor
                      superView:(UIView *)superView
                    constraints:(ZJConstrainMaker)constraints
{
    return [self zj_labelWithFontSize:fontSize lines:1 text:nil textColor:textColor superView:superView constraints:constraints];
}


+(instancetype)zj_labelWithFontSize:(CGFloat)fontSize
                           text:(NSString *)text
                      superView:(UIView *)superView
                    constraints:(ZJConstrainMaker)constraints
{
    return [self zj_labelWithFontSize:fontSize lines:1 text:text superView:superView constraints:constraints];
}

+(instancetype)zj_labelWithFontSize:(CGFloat)fontSize
                          lines:(NSInteger)lines
                           text:(NSString *)text
                      superView:(UIView *)superView
                    constraints:(ZJConstrainMaker)constraints
{
    return [self zj_labelWithFontSize:fontSize lines:lines text:text textColor:nil superView:superView constraints:constraints];
}

+(instancetype)zj_labelWithFont:(UIFont *)font
                          lines:(NSInteger)lines
                           text:(NSString *)text
                      textColor:(UIColor *)textColor
                      superView:(UIView *)superView
                    constraints:(ZJConstrainMaker)constraints
{
    return [self zj_initLabelWithFont:font fontSize:0 lines:lines text:text textColor:textColor superView:superView constraints:constraints];
}

+(instancetype)zj_labelWithFontSize:(CGFloat)fontsize
                          lines:(NSInteger)lines
                           text:(NSString *)text
                      textColor:(UIColor *)textColor
                      superView:(UIView *)superView
                    constraints:(ZJConstrainMaker)constraints
{
    return [self zj_initLabelWithFont:nil fontSize:fontsize lines:lines text:text textColor:textColor superView:superView constraints:constraints];
    
}

+(instancetype)zj_initLabelWithFont:(UIFont *)font
                   fontSize:(CGFloat)fontSize
                      lines:(NSInteger)lines
                       text:(NSString *)text
                  textColor:(UIColor *)textColor
                  superView:(UIView *)superView
                constraints:(ZJConstrainMaker)constraints{
    
    UILabel *label = [[UILabel alloc]init];
    label.text = text;
    if (fontSize!=0) {
        label.font = AdaptedFontSizeLabel(fontSize);
    }
    
    if (font != nil) {
        label.font = font;
    }
    
    label.textAlignment = NSTextAlignmentLeft;
    if (textColor != nil) {
        label.textColor = textColor;
    }else{
        label.textColor = [UIColor blackColor];
    }
    label.numberOfLines = lines;
    
    if (lines <= 0) {
        label.lineBreakMode = NSLineBreakByWordWrapping;
    } else {
        label.lineBreakMode = NSLineBreakByTruncatingTail;
    }
    
    [superView addSubview:label];
    
    if (superView && constraints) {
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            constraints(make);
        }];
    }
    return label;
}


- (void)setColumnSpace:(CGFloat)columnSpace
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    //调整间距
    [attributedString addAttribute:(__bridge NSString *)kCTKernAttributeName value:@(columnSpace) range:NSMakeRange(0, [attributedString length])];
    self.attributedText = attributedString;
}

- (void)setRowSpace:(CGFloat)rowSpace
{
    self.numberOfLines = 0;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    //调整行距
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = rowSpace;
    paragraphStyle.baseWritingDirection = NSWritingDirectionLeftToRight;
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.text length])];
    self.attributedText = attributedString;
}



-(NSString *)fontName
{
    return objc_getAssociatedObject(self, _cmd);
}
-(void)setFontName:(NSString *)fontName
{
    objc_setAssociatedObject(self, @selector(fontName), fontName, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(CGFloat)fontsize
{
    return [objc_getAssociatedObject(self,_cmd) floatValue];
}
-(void)setFontsize:(CGFloat)fontsize
{
    objc_setAssociatedObject(self, @selector(fontsize), @(fontsize), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(CGFloat)firstline{
    
    return [objc_getAssociatedObject(self,_cmd) floatValue];
}
-(void)setFirstline:(CGFloat)firstline
{
    objc_setAssociatedObject(self, @selector(firstline), @(firstline), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(CGFloat)characterSpace{
    return [objc_getAssociatedObject(self,_cmd) floatValue];
}

-(void)setCharacterSpace:(CGFloat)characterSpace{
    objc_setAssociatedObject(self, @selector(characterSpace), @(characterSpace), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
}

-(CGFloat)lineSpace{
    return [objc_getAssociatedObject(self, _cmd) floatValue];
}

-(void)setLineSpace:(CGFloat)lineSpace{
    objc_setAssociatedObject(self, @selector(lineSpace), @(lineSpace), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


-(NSString *)keywords{
    return objc_getAssociatedObject(self, _cmd);
}

-(void)setKeywords:(NSString *)keywords{
    objc_setAssociatedObject(self, @selector(keywords), keywords, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UIFont *)keywordsFont{
    return objc_getAssociatedObject(self, _cmd);
}

-(void)setKeywordsFont:(UIFont *)keywordsFont{
    objc_setAssociatedObject(self, @selector(keywordsFont), keywordsFont, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UIColor *)keywordsColor{
    return objc_getAssociatedObject(self, _cmd);
}

-(void)setKeywordsColor:(UIColor *)keywordsColor{
    objc_setAssociatedObject(self, @selector(keywordsColor), keywordsColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSString *)underlineStr{
    return objc_getAssociatedObject(self, _cmd);
}

-(void)setUnderlineStr:(NSString *)underlineStr{
    objc_setAssociatedObject(self, @selector(underlineStr), underlineStr, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
}

-(UIColor *)underlineColor{
    return objc_getAssociatedObject(self, _cmd);
}

-(void)setUnderlineColor:(UIColor *)underlineColor{
    objc_setAssociatedObject(self, @selector(underlineColor), underlineColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
}

/**
 *  根据最大宽度计算label宽，高
 *
 *  @param maxWidth 最大宽度
 *
 *  @return size
 */
- (CGSize)getLableSizeWithMaxWidth:(CGFloat)maxWidth{
    if (kIsEmptyString(self.text)) {
        return CGSizeMake(0, 0);
    }else{
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:self.text];
        [attributedString addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0,self.text.length)];
        
        if (self.fontsize!=0 && self.fontName!=nil) {
            UIFont *descFont = [UIFont fontWithName:self.fontName size:self.fontsize];
            if (descFont!=nil) {
                [attributedString addAttributes:@{NSFontAttributeName:descFont} range:NSMakeRange(0,self.text.length)];
            }
            
        }
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
        paragraphStyle.alignment=self.textAlignment;
        paragraphStyle.lineBreakMode=self.lineBreakMode;
        
        if (self.firstline>0) {
            paragraphStyle.firstLineHeadIndent = self.firstline;
        }
        // 行间距
        if(self.lineSpace > 0){
            [paragraphStyle setLineSpacing:self.lineSpace];
            [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,self.text.length)];
        }
        
        // 字间距
        if(self.characterSpace > 0){
            long number = self.characterSpace;
            CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);
            [attributedString addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(0,[attributedString length])];
            
            CFRelease(num);
        }
        
        //关键字
        if (self.keywords) {
            NSRange itemRange = [self.text rangeOfString:self.keywords];
            if (self.keywordsFont) {
                [attributedString addAttribute:NSFontAttributeName value:self.keywordsFont range:itemRange];
            }
            
            if (self.keywordsColor) {
                [attributedString addAttribute:NSForegroundColorAttributeName value:self.keywordsColor range:itemRange];
                
            }
        }
        
        //下划线
        if (self.underlineStr) {
            NSRange itemRange = [self.text rangeOfString:self.underlineStr];
            [attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:itemRange];
            if (self.underlineColor) {
                [attributedString addAttribute:NSUnderlineColorAttributeName value:self.underlineColor range:itemRange];
            }
        }
        
        
        
        self.attributedText = attributedString;
        
        //计算方法一
        //计算文本rect，但是发现设置paragraphStyle.lineBreakMode=NSLineBreakByTruncatingTail;后高度计算不准确
        //CGRect rect = [attributedString boundingRectWithSize:CGSizeMake(maxWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
        
        //计算方法二
        CGSize maximumLabelSize = CGSizeMake(maxWidth, MAXFLOAT);//labelsize的最大值
        CGSize expectSize = [self sizeThatFits:maximumLabelSize];
        
        return expectSize;
    }
   
}

@end
